package com.s59.Service;

import com.s59.dao.BookDao;
import com.s59.entity.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.domain.Example;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class BookService {
    @Autowired
    private BookDao bookDao;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    public static final String SK_BOOK_KEY = "sk_book";

    public boolean cacheBook() {
        Book book = new Book();
        book.setSecondsKill(1);
        Example<Book> example = Example.of(book);
        List<Book> list = bookDao.findAll(example);
        Map<String,String> map = new HashMap<>();
        for (Book book1 : list) {
            map.put(book1.getId().toString(),"10");
        }
        stringRedisTemplate.opsForHash().putAll(SK_BOOK_KEY,map);
        return true;
    }

    public boolean chearBook() {
        return stringRedisTemplate.delete(SK_BOOK_KEY).booleanValue();
    }

    public Book findById(Long bookId) {
        return bookDao.findById(bookId).get();
    }

    public void modifyStock(Long bookId, int i) {
        Book book = this.findById(bookId);
        book.setAmount(book.getAmount() + i);
        bookDao.save(book);
    }
}
